package com.zhongcw.spring.transaction.service;

import com.zhongcw.spring.transaction.po.Commodity;
import com.zhongcw.spring.transaction.repository.CommodityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @author ZCW
 * @createTime 2018/1/5
 * @lastUpdateTime 2018/1/5 ZCW
 */
@Service
public class CommodityService {

    @Autowired
    CommodityRepository commodityRepository;

    @Autowired
    CommodityService commodityService;

    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false)
    public Boolean updateCommodityLastUpdateTime(Commodity commodity) {
        Commodity comm = commodityRepository.findOne(commodity.getId());
        comm.setLastUpdateTime(new Date());
//        commodity = commodityRepository.save(commodity);
        return Objects.nonNull(comm);
    }

    @Transactional
    public void updateCommodityById(String id) {
        Commodity commodity = commodityRepository.findOne(id);
        System.err.println("\n start updateCommodityLastUpdateTime()");
        commodityService.sleep();
        commodityService.updateCommodityLastUpdateTime(commodity);
        // 直接调用当前类的方法，其事务注解并不会生效
//        updateCommodityLastUpdateTime(commodity);
        commodityService.sleep();
        System.err.println("\n end updateCommodityLastUpdateTime()");
    }

    public static void sleep() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
